<template>
  <view class="trip-view">
    <!-- 旅程目的地和搜索 -->
    <view class="trip-serch-box">
      <!-- 出发地和目的地选择 -->
      <view class="place-box">
        <picker mode="multiSelector" @cancel="removeDeparture" @change="bindMultiPickerChangeDeparture" @columnchange="bindMultiPickerColumnChangeDeparture" :value="data.departureIndex" :range="data.departure" range-key="label">
          <view class="place-item" v-if="data.departureId != ''">{{data.placeList[data.departureIndex[0]].label}}-{{data.placeList[data.departureIndex[0]].cityList[data.departureIndex[1]].label}}</view>
          <view class="place-item" v-if="data.departureId == ''">出发地</view>
        </picker>
        <view>———▶</view>
        <picker mode="multiSelector" @cancel="removeDestination"  @change="bindMultiPickerChangeDestination" @columnchange="bindMultiPickerColumnChangeDestination" :value="data.destinationIndex" :range="data.destination" range-key="label">
          <view class="place-item" v-if="data.destinationId != ''">{{data.placeList[data.destinationIndex[0]].label}}-{{data.placeList[data.destinationIndex[0]].cityList[data.destinationIndex[1]].label}}</view>
          <view class="place-item" v-if="data.destinationId == ''">目的地</view>
        </picker>
      </view>
      <!-- 搜索栏 -->
      <view class="search-box">
        <input class="s-input" confirm-type="search" placeholder="搜索" v-model="data.searchText"/>
        <view class="s-button" @click="searchTripNew">搜索</view>
      </view>
    </view>
    <!-- 旅程资讯 -->
    <view>
      <scroll-view scroll-y="true" class="trip-new" lower-threshold="50" @scrolltolower="getMoreTripNew">
        <view class="trip-item" @click="showTripNew(item.id,index)" v-for="(item,index) in data.tripNewList" :key="index">
          <image mode="aspectFill" class="trip-img" :src="item.cover"></image>
          <view class="trip-des">
            <text class="trip-title">{{item.title}}</text>
            <text class="trip-road">{{item.departure}}->{{item.destination}}</text>
            <text class="trip-road">{{item.startTime}}->{{item.dayNum}}天</text>
            <view class="trip-info">
              <view class="author-info">
                <image class="trip-avatar" :src="item.authorAvatar"></image>
                <text class="trip-name">{{item.authorName}}</text>
              </view>
              <view class="trip-like-box" @click.stop="likeTripNew(index)">
                <image class="trip-like" v-if="item.like == 0 || item.like == null" src="../../static/img/like-btn1.png"></image>
                <image class="trip-like" v-else src="../../static/img/like-btn2.png"></image>
                <text class="trip-like-num">{{item.likeNum}}</text>
              </view>
              
            </view>
          </view>
        </view>
        <view class="tip-tag" v-if="data.tripNewList.length >= data.total">
          暂无更多了
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,onMounted } from 'vue';
import { onShow,onLoad,onUnload,onHide } from '@dcloudio/uni-app'
import helper from '../../common/helper.js'
 
const data = reactive({
 searchText:"",
 departure:[],
 departureIndex: [0,0],
 departureId: "",
 destination:[],
 destinationIndex: [0,0],
 destinationId: "",
 placeList:[],
 childArr:[],
 tripNewList:[],
 total:0,
 pageNum:0,
 pageSize:10,
});

onShow(()=>{
  //监听页面返回的点赞事件
  getPlace()
  updateLikeData()
})

function initData(){
  data.searchText=""
  data.departure=[]
  data.departureIndex= [0,0]
  data.departureId= ""
  data.destination=[]
  data.destinationIndex= [0,0]
  data.destinationId= ""
  data.placeList=[]
  data.childArr=[]
  data.tripNewList=[]
  data.total=0
  data.pageNum=0
  data.pageSize=10
}

onUnload((options)=>{
  uni.$off('like');  
})

function updateLikeData(){
  uni.$on('like',(likeData)=>{
    if(likeData.event == 2){
      //我的笔记或资讯
      console.log("点赞事件:资讯"+likeData.index+" "+likeData.like)
      if(data.tripNewList[likeData.index].like < likeData.like){
        data.tripNewList[likeData.index].likeNum++
      }else if(data.tripNewList[likeData.index].like > likeData.like){
        data.tripNewList[likeData.index].likeNum--
      }
      data.tripNewList[likeData.index].like = likeData.like
    }
  })
}

function getPlace(){
  uni.request({
      url: helper.webUrl + "/tripNew/getPlace",
      method:'GET',
      success: (res) => {
        console.log(res.data);
        data.placeList = res.data.data
        for (let i = 0; i < data.placeList.length; i++) {
          // 将数据源中的二级分类 push 进 childArr，作为二级分类的数据源
          data.childArr.push(data.placeList[i].cityList)
        }; 
        // 一级分类的数据源
        data.departure[0] = data.placeList
        data.destination[0] = data.placeList
        
         // 第一次打开时，默认给一级分类添加它的二级分类
        data.departure[1] = data.childArr[0]
        data.destination[1] = data.childArr[0]
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
}

function removeDeparture(){
  data.departureId = ''
}

function removeDestination(){
  data.destinationId = ''
}

function bindMultiPickerChangeDeparture(e){
  console.log('出发地改变，携带值为', e.detail.value)
  data.departureId = data.placeList[e.detail.value[0]].cityList[e.detail.value[1]].id
  console.log(data.departureId)
}

function bindMultiPickerColumnChangeDeparture(e){
  if(!data.departureIndex || !data.departureIndex.length){
  		data.departureIndex = [0,0]
  	}
  	
  	let column = e.detail.column;
  	let value = e.detail.value;
  	console.log(column , value);
  	
  	let departureIndex = data.departureIndex;
  	departureIndex[column] = value;
  	if(column == 0){
  		departureIndex[1] = 0;
  	}
  	data.departureIndex = departureIndex;
  	
  	let departure = [];
  	departure[0] = data.placeList;
  	departure[1] = data.placeList[departureIndex[0]].cityList;
  	data.departure = departure;
}

function bindMultiPickerColumnChangeDestination(e){
  if(!data.destinationIndex || !data.destinationIndex.length){
  		data.destinationIndex = [0,0]
  	}
  	
  	let column = e.detail.column;
  	let value = e.detail.value;
  	console.log(column , value);
  	
  	let destinationIndex = data.destinationIndex;
  	destinationIndex[column] = value;
  	if(column == 0){
  		destinationIndex[1] = 0;
  	}
  	data.destinationIndex = destinationIndex;
  	
  	let destination = [];
  	destination[0] = data.placeList;
  	destination[1] = data.placeList[destinationIndex[0]].cityList;
  	data.destination = destination;
}

function bindMultiPickerChangeDestination(e){
  console.log('目的地改变，携带值为', e.detail.value)
  data.destinationId = data.placeList[e.detail.value[0]].cityList[e.detail.value[1]].id
  console.log(data.destinationId)
}

function bindPickerChange(e) {
  console.log('天数picker发送选择改变，携带值为', e.detail.value)
  data.dayIndex = e.detail.value
}

function searchTripNew(){
  if(data.searchText == "" && data.searchText.trim() == "" && data.departureId == "" && data.destinationId == ""){
    return
  }
  data.pageNum = 0
  data.pageSize = 10
  data.tripNewList = []
  data.total = 0
  getTripNewWidthKeyWord()
}

function getTripNewWidthKeyWord(){
  uni.request({
      url: helper.webUrl+'/tripNew/getTripNewWidthKeyWord', 
      method:'GET',
      header:{
        'token': helper.getToken()
      },
      data: {
        keyWord: data.searchText,
        departureId:data.departureId,
        destinationId:data.destinationId,
        pageNum:data.pageNum,
        pageSize:data.pageSize,
      },
      success: (res) => {
        console.log(res.data);
        //处理笔记数据
        if(res.data.code == 200){
          let list = res.data.data.record
          data.total = res.data.data.total
          data.pageNum++
          for(let i = 0; i < list.length; i++){
            list[i].startTime = helper.getDate(list[i].startTime)
            data.tripNewList.push(list[i])
          }
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
  });
}

function getMoreTripNew(){
  if(data.total <= data.tripNewList.length){
    return
  }
  getTripNewWidthKeyWord()
}

function showTripNew(tripNewId,index){
  console.log("查看资讯"+tripNewId)
  uni.navigateTo({
    url:`/subpages/tripNew/tripNew?tripNewId=${tripNewId}&index=${index}&event=2`
  })
}

async function likeTripNew(index){
  console.log("点赞资讯")
  console.log(data.tripNewList[index].like)
  if(helper.getToken() == null){
    return
  }
  if(data.tripNewList[index].like > 0){
  let res = await helper.dislikeTripNewReq(data.tripNewList[index].id)
    if(res.data.code == 200){
      data.tripNewList[index].like = 0
      data.tripNewList[index].likeNum--
    }
  }else{
    let res = await helper.likeTripNewReq(data.tripNewList[index].id)
    if(res.data.code == 200){
      data.tripNewList[index].like = 1
      data.tripNewList[index].likeNum++
    }
  }
}
</script>

<style scoped>
.trip-view{
  width: 100vw;
  background-color: #f4f4f4;
}
.trip-serch-box{
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100vw;
  height: 35vh;
  background-image: url("../../static/img/trip.jpg");
  background-size: cover; /* 根据需要调整背景图片大小 */
  background-position: center; /* 根据需要调整背景图片位置 */
  background-repeat: no-repeat; /* 根据需要设置是否重复 */
}
.place-box{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 60px;
}
.place-item{
  font-size: 30px;
  padding-inline: 20px;
  font-weight: bold;
}
.search-box{
  width: 90vw;
  height: 8vh;
  border-top-left-radius: 100px;
  border-bottom-left-radius: 100px;
  margin-inline: auto;
  margin-top: 10px;
  background-color: #fff;
  display: flex;
}
.s-input{
  padding-left: 25px;
  font-size: 18px;
  width: 70%;
  height: 100%;
}
.s-button{
  width: 25%;
  height: 100%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top-right-radius: 100px;
  border-bottom-right-radius: 100px;
}
</style>
